from format_check import *
from exts import UserMongodb , all_logger
class UserModel:
    def __init__(self, username, password, email, grade, major, name, is_admin, codeforces_id=None, phone_number=None,
                 atcoder_id=None, nowcoder_id=None, luogu_id=None, vjudge_id=None):
        # 验证基本信息
        try:
            self.username = StringField(max_length=20, min_length=5, required=True).validate(username , "username")
            self.password = StringField(max_length=20, min_length=5,required=True).validate(password , "password")
            self.email = EmailField(required=True).validate(email)
            self.phone_number = StringField(min_length=11, max_length=11,required=True).validate(phone_number , "phone_number")
            self.grade = StringField(required=True).validate(grade , "grade")
            self.major = StringField(required=True).validate(major, "major")
            self.name = StringField(required=True).validate(name, "name")
            self.is_admin = BooleanField(required=True).validate(is_admin, "is_admin")
        except Exception as e:
            # 若验证出错，返回错误信息
            all_logger.error(f"错误类型: {type(e)} 错误信息: {str(e)}")
            raise Exception("Error validating fields: " + str(e))
            # return f"Error validating fields: {str(e)}", 400
        try:
            self.rating = None

            # 验证账号信息
            self.codeforces_id = StringField(max_length=100).validate(codeforces_id)
            self.codeforces_solve_number = None
            self.codeforces_rating = None

            self.atcoder_id = StringField(max_length=100).validate(atcoder_id)
            self.atcoder_rating = None
            self.atcoder_solve_number = None

            self.nowcoder_id = StringField(max_length=100).validate(nowcoder_id)
            self.nowcoder_rating = None
            self.nowcoder_solve_number = None

            self.luogu_id = StringField(max_length=8).validate(luogu_id)
            self.luogu_rating = None
            self.luogu_solve_number = None

            self.vjudge_id = StringField().validate(vjudge_id)
            self.vjudge_solve_number = None

            # 现役 / 退役
            self.active_service = BooleanField().validate(True)

            # 排位赛列表
            self.ranking_contest_list = []
            # 1. 比赛链接
            # 2. 比赛平台
            # 3. 比赛名
            # 4. 比赛开始时间
            # 5. 比赛结束时间
            # 6. 比赛类型 ACM / IOI / OI
            # 7. 记入榜单 / 不记入榜单 rating
            # 8. 特殊榜单选择 / 不选
            # 9. 特殊榜单占比
            # 10. ranking / scores
            # 11. ranking
            # 12. scores

            # 补题/日常任务
            self.daily_task_list = []
            # 1. 比赛链接
            # 2. 比赛平台
            # 3. 比赛名
            # 4. 比赛开始时间
            # 5. 比赛结束时间
            # 6. 比赛类型 ACM / IOI / OI
            # 7. 记入榜单 / 不记入榜单 rating
            # 8. 特殊榜单选择 / 不选
            # 9. 特殊榜单占比
            # 10. ranking / scores
            # 11. ranking
            # 12. scores
            self.create_time = DateField().validate()
            all_logger.info(f"创建用户 {self.username} 成功")
        except Exception as e:
            # 若验证出错，返回错误信息
            all_logger.error(f"错误类型: {type(e)} 错误信息: {str(e)}"  )
            raise Exception(f"Error validating fields: {e}" )
            # return f"Error validating fields: {str(e)}", 400

    def get_user_info(self):
        return {
            'username': self.username,
            'password': self.password,
            'email': self.email,
            'phone_number': self.phone_number,
            'grade': self.grade,
            'major': self.major,
            'name': self.name,
            'is_admin': self.is_admin,
            'codeforces_id': self.codeforces_id,
            'codeforces_solve_number': self.codeforces_solve_number,
            'codeforces_rating': self.codeforces_rating,
            'atcoder_id': self.atcoder_id,
            'atcoder_rating': self.atcoder_rating,
            'atcoder_solve_number': self.atcoder_solve_number,
            'nowcoder_id': self.nowcoder_id,
            'nowcoder_rating': self.nowcoder_rating,
            'nowcoder_solve_number': self.nowcoder_solve_number,
            'luogu_id': self.luogu_id,
            'luogu_rating': self.luogu_rating,
            'luogu_solve_number': self.luogu_solve_number,
            'vjudge_id': self.vjudge_id,
            'vjudge_solve_number': self.vjudge_solve_number,
            'active_service': self.active_service,
            'ranking_contest_list': self.ranking_contest_list,
            'daily_task_list': self.daily_task_list,
            'create_time': self.create_time,
            'rating': self.rating,
        }
    def get_user_basic_info(self):
        return {
            'username': self.username,
            'password': self.password,
            'email': self.email,
            'phone_number': self.phone_number,
            'grade': self.grade,
            'major': self.major,
            'name': self.name,
            'is_admin': self.is_admin,
            'codeforces_id': self.codeforces_id,
            'codeforces_solve_number': self.codeforces_solve_number,
            'codeforces_rating': self.codeforces_rating,
            'atcoder_id': self.atcoder_id,
            'atcoder_rating': self.atcoder_rating,
            'atcoder_solve_number': self.atcoder_solve_number,
            'nowcoder_id': self.nowcoder_id,
            'nowcoder_rating': self.nowcoder_rating,
            'nowcoder_solve_number': self.nowcoder_solve_number,
            'luogu_id': self.luogu_id,
            'luogu_rating': self.luogu_rating,
            'luogu_solve_number': self.luogu_solve_number,
            'vjudge_id': self.vjudge_id,
            'vjudge_solve_number': self.vjudge_solve_number,
            # 'active_service': self.active_service,
            # 'ranking_contest_list': self.ranking_contest_list,
            # 'daily_task_list': self.daily_task_list,
            # 'create_time': self.create_time,
            # 'rating': self.rating,
        }
    def save(self):
        if UserMongodb.find_one({'username': self.username}):
            all_logger.error('用户名已存在')
            raise Exception('用户名已存在')
        elif UserMongodb.find_one({'email': self.email}):
            all_logger.error('邮箱已存在')
            raise Exception('邮箱已存在')
        elif UserMongodb.find_one({'phone_number': self.phone_number}):
            all_logger.error('手机号已存在')
            raise Exception('手机号已存在')
        elif UserMongodb.find_one({'codeforces_id': self.codeforces_id}):
            all_logger.error('Codeforces ID已存在')
            raise Exception('Codeforces ID已存在')
        elif UserMongodb.find_one({'atcoder_id': self.atcoder_id}):
            all_logger.error('AtCoder ID已存在')
            raise Exception('AtCoder ID已存在')
        elif UserMongodb.find_one({'nowcoder_id': self.nowcoder_id}):
            all_logger.error('NowCoder ID已存在')
            raise Exception('NowCoder ID已存在')
        elif UserMongodb.find_one({'luogu_id': self.luogu_id}):
            all_logger.error('Luogu ID已存在')
            raise Exception('Luogu ID已存在')
        elif UserMongodb.find_one({'vjudge_id': self.vjudge_id}):
            all_logger.error('VJudge ID已存在')
            raise Exception('VJudge ID已存在')
        else:
            UserMongodb.insert_one(self.get_user_info())
            all_logger.info('用户注册成功')
    def update_basic_info(self):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                {'$set': self.get_user_basic_info()}
            )
            all_logger.info('用户基础信息更新成功')
        else:
            all_logger.error('用户不存在,基础信息更新失败')
            raise Exception('用户不存在')
    def update_active_service_info(self , active_service_cp ):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                {'$set': {'active_service': active_service_cp }}
            )
            all_logger.info('用户现役信息更新成功')
        else:
            raise Exception('用户不存在,用户现役信息更新失败')
    def update_rating_info(self,new_rating):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                {'$set': {'rating': new_rating }}
            )
            all_logger.info('用户rating信息更新成功')
        else:
            all_logger.error('用户不存在,用户rating信息更新失败')
            raise Exception('用户不存在,用户rating信息更新失败')
    def update_ranking_contest_info(self,new_ranking_contest):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                {'$addToSet': {'ranking_contest_list': new_ranking_contest }}
            )
            all_logger.info('用户排名比赛信息更新成功')
        else:
            all_logger.error('用户不存在,用户排名比赛信息更新失败')
            raise Exception('用户不存在,用户排名比赛信息更新失败')
    def delete_ranking_contest_info(self,old_ranking_contest):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                # old_ranking_contest 是一个字典，表示选择什么为被删除属性
                {'$pull': {'ranking_contest_list': old_ranking_contest }}
            )
            all_logger.info('用户排名比赛信息删除成功')
        else:
            all_logger.error('用户不存在,用户排名比赛信息删除失败')
            raise Exception('用户不存在,用户排名比赛信息删除失败')
    def update_daily_task_info(self,new_daily_task):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                {'$addToSet': {'daily_task_list': new_daily_task }}
            )
            all_logger.info('用户每日任务信息更新成功')
        else:
            all_logger.error('用户不存在,用户每日任务信息更新失败')
            raise Exception('用户不存在,用户每日任务信息更新失败')
    def delete_daily_task_info(self,old_daily_task):
        if UserMongodb.find_one({'username': self.username}):
            UserMongodb.update_one(
                {'username': self.username},
                {'$pull' : {'daily_task_list': old_daily_task}}
            )
            all_logger.info('用户每日任务信息删除成功')
        else:
            all_logger.error('用户不存在,用户每日任务信息删除失败')
    def get_info_Mongodb(self,username):
        user_info = UserMongodb.find_one({'username': username})
        if user_info:
            self.username = user_info['username']
            self.password = user_info['password']
            self.email = user_info['email']
            self.phone_number = user_info['phone_number']
            self.codeforces_id = user_info['codeforces_id']
            self.atcoder_id = user_info['atcoder_id']
            self.nowcoder_id = user_info['nowcoder_id']
            self.luogu_id = user_info['luogu_id']
            self.vjudge_id = user_info['vjudge_id']
            self.active_service = user_info['active_service']
            self.rating = user_info['rating']
            self.ranking_contest_list = user_info['ranking_contest_list']
            self.daily_task_list = user_info['daily_task_list']

            all_logger.info('用户信息获取成功')
            return user_info
        else:
            all_logger.error('用户不存在,username不正确')
            raise Exception('用户不存在,username不正确')


basic_user_class ={
    'username' : "S_zhi",
    'password' : "12345678",
    'email' : "S_zhi@163.com",
    'phone_number' : "12345678901",
    'major': "计算机科学与技术",
    'grade': "2021",
    'name': "S_zhi",
    'is_admin' : True

}
def get_all_user_class_list_from_Mongodb():
    all_user_class = []
    for user in UserMongodb.find():
        usermodel = UserModel( username=basic_user_class['username'] , password=basic_user_class['password'],email= basic_user_class['email'],
                   phone_number= basic_user_class['phone_number'],major= basic_user_class['major'],
                   grade= basic_user_class['grade'],name= basic_user_class['name'] ,is_admin= basic_user_class['is_admin'])
        username = user['username']
        usermodel.get_info_Mongodb(username)
        all_user_class.append(usermodel)
    return all_user_class
